package cn.wolfcode.shop.member.web.resolver;

import cn.wolfcode.cloud.redis.RedisService;
import cn.wolfcode.shop.member.domain.User;
import cn.wolfcode.shop.member.redis.MemberKeyPrefix;
import cn.wolfcode.shop.member.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Member;

@Component
public class UserHandlerMethodResolver  implements HandlerMethodArgumentResolver {

    @Autowired
    private RedisService redisService;

    /* 对于方法上的参数是否需要当前的解析器进行参数封装*/
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType()==User.class;
    }

    @Override
    public User resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //拿到cookie中的token信息
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        String token = CookieUtil.getCookieValue(request, "token");
        if(StringUtils.isEmpty(token)){
            return null;
        }
        // 从redis中获取到用户信息
        User user = redisService.get(MemberKeyPrefix.MEMBER_TOKEN, token, User.class);
        return user;
    }
}
